package com.xiaoxie.boot.utils;

import com.xiaoxie.boot.bean.Menu;
import com.xiaoxie.boot.bean.MenuInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author xiaoxie
 * @create 2022-03-20 22:42
 */
@Slf4j
public class TreeUtil {
    public static List<Menu> toTree(List<Menu> treeList, Integer pid) {
        List<Menu> retList = new ArrayList<Menu>();
        for (Menu parent : treeList) {
            if (pid.equals(parent.getPid())) {
                retList.add(findChildren(parent, treeList));
            }
        }
        return retList;
    }

    private static Menu findChildren(Menu parent, List<Menu> treeList) {
        List<Menu> childList = new ArrayList<>();
        for (Menu child : treeList) {
            if (parent.getId().equals(child.getPid())) {
                if (parent.getChild() == null) {
                    parent.setChild(childList);
                }
                parent.getChild().add(child);
            }
        }
        return parent;
    }

    public static List<MenuInfo> toTree1(List<MenuInfo> treeList, Integer pid) {
        List<MenuInfo> retList = new ArrayList<MenuInfo>();
        for (MenuInfo parent : treeList) {
            if (pid.equals(parent.getPid())) {
                retList.add(findChildren1(parent, treeList));
            }
        }
        return retList;
    }

    private static MenuInfo findChildren1(MenuInfo parent, List<MenuInfo> treeList) {
        List<MenuInfo> childList = new ArrayList<>();
        for (MenuInfo child : treeList) {
            if (parent.getId().equals(child.getPid())) {
                if (parent.getChildren() == null) {
                    parent.setChildren(childList);
                }
                parent.getChildren().add(child);
            }
        }
        return parent;
    }
}
